package com.it.gw.modules.station.viewmodel

import DictVo
import EquimentVo
import GWRunningStaticVo
import PictureVo
import android.util.Log
import com.it.common.bean.CommonBean
import com.it.common.bean.ResultBean
import com.it.common.livedata.UnPeekLiveData
import com.it.common.utils.LogUtil
import com.it.common.utils.isNotEmpty
import com.it.data.base.BaseViewModel
import com.it.data.manager.DataManager
import com.it.data.network.Api
import com.it.data.network.req.DealOrderDetailDto
import com.it.data.network.req.PicDto
import com.it.data.network.req.ProblemUploadDto
import com.it.data.network.req.SaveQuePicDto
import com.it.data.network.req.UploadFileDto
import com.it.data.network.rsp.GQStationVo
import com.it.data.network.rsp.GQYWXXVo
import com.it.data.network.rsp.InsertqueGQVo
import com.it.data.network.rsp.MyWorkOrderVo
import com.it.data.network.rsp.PageVo
import com.it.data.network.rsp.QuaTypeCountVo
import com.it.data.network.rsp.QuaTypeShellVo
import com.it.data.network.rsp.SttpVo
import com.it.data.network.rsp.UnresolvedVo
import com.it.data.network.rsp.WrongRecVo
import com.it.data.network.rsp.WtGQVo
import com.it.data.utils.HttpParamUtil


class GQStationViewModel : BaseViewModel() {

    val pageGQStationVoListLiveData by lazy { UnPeekLiveData<CommonBean<PageVo<List<GQStationVo>>>>() }
    val pageWtGQVoListLiveData by lazy { UnPeekLiveData<CommonBean<PageVo<List<WtGQVo>>>>() }
    val sttpVoListLiveData by lazy { UnPeekLiveData<CommonBean<List<SttpVo>>>() }
    val dictListLiveData by lazy { UnPeekLiveData<CommonBean<List<DictVo>>>() }
    val updateGQYWXXLiveData by lazy { UnPeekLiveData<CommonBean<String>>() }
    val pictureVoListLiveData by lazy { UnPeekLiveData<CommonBean<List<PictureVo>>>() }

    val insertqueGQLiveData by lazy { UnPeekLiveData<CommonBean<InsertqueGQVo>>() }

    val unresolvedVoLiveData by lazy { UnPeekLiveData<CommonBean<UnresolvedVo>>() }

    val resolvedVoLiveData by lazy { UnPeekLiveData<CommonBean<UnresolvedVo>>() }

    val myWorkOrderVoListLiveData by lazy { UnPeekLiveData<CommonBean<PageVo<List<MyWorkOrderVo>>>>() }

    val myWorkOrderVoLiveData by lazy { UnPeekLiveData<CommonBean<MyWorkOrderVo>>() }

    val dealOrderDetailLiveData by lazy { UnPeekLiveData<CommonBean<Any>>() }


    val quaTypeCountListLiveData by lazy { UnPeekLiveData<CommonBean<List<QuaTypeCountVo>>>() }

    val wrongRecVoListLiveData by lazy { UnPeekLiveData<CommonBean<PageVo<List<WrongRecVo>>>>() }

    val gwRunningStaticVoListLiveData by lazy { UnPeekLiveData<CommonBean<List<GWRunningStaticVo>>>() }

    /**
     *查询测站列表
     * @param userId String
     * @param pageNum Int
     * @param pageSize Int
     * @param addvcd String 行政区规划
     * @param sttp String  测站类型
     * @param projecttype String 数据来源
     * @param quedeal Int 运维状态 1 正常 0 问题
     * @param stnm String 查询条件（测站编码或者名称）
     * @return ResultBean<PageVo<List<GQStationVo>>>
     */
    fun getGQStationList(
        userId: String,
        pageNum: Int,
        pageSize: Int,
        addvcd: String? = null,
        sttp: String? = null,
        projecttype: String? = null,
        quedeal: String? = null,
        stnm: String? = null,
    ) {
        requestCommit(request = {
            val list = mutableListOf<String>()
            list.add(userId)
            list.add(pageNum.toString())
            list.add(pageSize.toString())


            var url = HttpParamUtil.buildStationListUrl(list, Api.GET_GQSTATIONLIST)
            Api.apiClient()
                .getGQStationList(
                    url,
                    addvcd = addvcd,
                    sttp = sttp,
                    projecttype = projecttype,
                    quedeal = quedeal,
                    stnm = stnm,
                )
        }, resp = {
            pageGQStationVoListLiveData.postValue(it)
        })
    }

    /**
     * 运维记录列表
     * @param pageNum Int
     * @param pageSize Int
     * @param trcd String?
     * @param stcd String
     * @param queType String?
     * @param queDeal Int?
     * @param type Int?
     */
    fun getWtGQ(
        pageNum: Int,
        pageSize: Int,
        trcd: String? = null,
        stcd: String,
        queType: String? = null,
        queDeal: String? = null,
        type: Int? = null,
    ) {
        Log.d(TAG, "getWtGQ: queType ${queType}")
        requestCommit(request = {
            val list = mutableListOf<String>()
            list.add(pageNum.toString())
            list.add(pageSize.toString())
            var url = HttpParamUtil.buildStationListUrl(list, Api.GET_WTGQ)
            Api.apiClient()
                .getWtGQ(
                    url,
                    stcd = stcd,
                    trcd = trcd,
                    queDeal = queDeal,
                    queType = queType,
                    type = type
                )
        }, resp = {
            pageWtGQVoListLiveData.postValue(it)
        })
    }

    fun getSttp(resp: ((CommonBean<List<SttpVo>>) -> Unit)? = null) {
        requestCommit(request = {
            Api.apiClient().getSttp()
        }, resp = {
            resp?.invoke(it)
            sttpVoListLiveData.postValue(it)
        })
    }


    fun getDictName(mode: String, resp: ((CommonBean<List<DictVo>>) -> Unit)? = null) {
        requestCommit(request = {
            Api.apiClient().getDictName(mode)
        }, resp = {
            resp?.invoke(it)
            dictListLiveData.postValue(it)
        })
    }

    //RTU品牌型号，rtuModel
    //蓄电池品牌型号，xdcModel
    //蓄电池容量，xdcrlModel

    //太阳能板品牌，tynbModel
    //太阳能板功率，tynbglModel
    //流量计品牌型号，lljModel

    //量水设施类型，lsssType
    //雨量筒型号，yltModel
    //水位计品牌型号，swjModel

    //通讯模块品牌型号，txmkModel
    //充电控制器品牌型号，cdkzqModel
    //摄像头品牌型号，sxtModel
    //土壤墒情传感器，soil
    val nodeList = mutableListOf<String>(
        "rtuModel",
        "xdcModel",
        "xdcrlModel",
        "tynbModel",
        "tynbglModel",
        "lljModel",
        "LSSS_TYPE",
        "yltModel",
        "swjModel",
        "txmkModel",
        "cdkzqModel",
        "sxtModel",
        "soil",

        )


    fun initDictMap() {
        DataManager.dictMap.clear()
        nodeList.forEach {
            initDict(mode = it)
        }
    }

    fun initDict(mode: String) {
        requestCommit(request = {
            Api.apiClient().getDictName(mode)
        }, resp = {
            if (it.result && it.data.isNotEmpty()) {
                DataManager.dictMap.put(mode, it.data!!)
                Log.d(TAG, "initDict: ${DataManager.dictMap}")
            }

        })
    }

    suspend fun getDicValueByModelAndCode(mode: String, code: String): String? {
        try {
            val res = Api.apiClient().getDictName(mode)
            Log.d(TAG, "getDicValueByModelAndCode: ==============${res.data}")
            val dataValue = res.data?.find { it.dataCode == code }?.dataName
            Log.d(TAG, "getDicValueByModelAndCode: ${mode} ${code} ${dataValue}")
            return dataValue
        } catch (e: Exception) {
            LogUtil.d(TAG, "getDicValueByModelAndCode e ${e.message}")
            return ""
        }


    }


    fun updateGQYWXX(vo: GQYWXXVo, resp: ((CommonBean<String?>) -> Unit)? = null) {
        requestCommit(request = {
            Api.apiClient().updateGQYWXX(vo)
        }, resp = {
            updateGQYWXXLiveData.postValue(it)
        })
    }

    /**
     * 获取站点图片列表
     */
    fun getGQPicByStcd(STCD: String) {
        requestCommit(request = {
            Api.apiClient().getGQPicByStcd(STCD)
        }, resp = {
            pictureVoListLiveData.postValue(it)
        })
    }


    suspend fun saveGQStcdPic(
        dto: PicDto,
        uploadFileDtoList: MutableList<UploadFileDto>,
    ): ResultBean<String> {
        Log.d(TAG, "uploadPic: uploadFileDtoList${uploadFileDtoList}")
        val res = Api.apiClient()
            .saveGQStcdPic(
                HttpParamUtil.filesToMultipartBody(
                    vo = dto,
                    uploadFileDtoList = uploadFileDtoList,
                    mediaType = "*/*"
                )
            )
        return res
    }


    suspend fun saveQuePic(
        dto: SaveQuePicDto,
        uploadFileDtoList: MutableList<UploadFileDto>,
    ): ResultBean<String> {
        Log.d(TAG, "uploadPic:dto ${dto} uploadFileDtoList${uploadFileDtoList}")
        val res = Api.apiClient()
            .saveQuePic(
                HttpParamUtil.filesToMultipartBody(
                    vo = dto,
                    uploadFileDtoList = uploadFileDtoList,
                    mediaType = "*/*"
                )
            )
        return res
    }

    fun getQuaTypeSell(
        sttp: String,
        queId: String,
        resp: ((CommonBean<List<QuaTypeShellVo>>) -> Unit)? = null
    ) {
        requestCommit(request = {
            Api.apiClient().getQuaTypeSell(sttp = sttp, queId = queId)
        }, resp = {
            resp?.invoke(it)
        })
    }

    fun equipment(
        sttp: String,
        stcd: String,
        id: String,
        resp: ((CommonBean<List<EquimentVo>>) -> Unit)? = null
    ) {
        requestCommit(request = {
            Api.apiClient().equipment(sttp = sttp, stcd = stcd, id = id)
        }, resp = {
            resp?.invoke(it)
        })
    }


    fun insertqueGQ(vo: ProblemUploadDto) {
        requestCommit(request = {
            Api.apiClient().insertqueGQ(vo)
        }, resp = {
            insertqueGQLiveData.postValue(it)
        })
    }


    fun getUnresolved(
        sttp: String,
        stcd: String,
        id: String
    ) {
        requestCommit(request = {
            Api.apiClient().getUnresolved(sttp = sttp, stcd = stcd, id = id)
        }, resp = {
            unresolvedVoLiveData.postValue(it)
        })
    }

    fun getResolved(
        sttp: String,
        stcd: String,
        id: String
    ) {
        requestCommit(request = {
            Api.apiClient().getResolved(sttp = sttp, stcd = stcd, id = id)
        }, resp = {
            unresolvedVoLiveData.postValue(it)
        })
    }


    fun getListByUserId(
        pageNum: Int,
        pageSize: Int,
        addvcd: String? = null,
        status: String? = null,
        orderType: String? = null,
        stcd: String? = null,


        ) {
        requestCommit(request = {
            Api.apiClient()
                .getListByUserId(
                    pageNo = pageNum,
                    pageSize = pageSize,
                    addvcd = addvcd,
                    stcd = stcd,
                    status = status,
                    orderType = orderType,

                    )
        }, resp = {
            myWorkOrderVoListLiveData.postValue(it)
        })
    }

    fun getOrderDetailById(
        orderDetailId: String,
    ) {
        requestCommit(request = {
            Api.apiClient()
                .getOrderDetailById(
                    orderDetailId = orderDetailId,
                )
        }, resp = {
            myWorkOrderVoLiveData.postValue(it)
        })
    }

    /**
     * 处理订单
     * @param dto DealOrderDetailDto
     */
    fun dealOrderDetail(
        dto: DealOrderDetailDto,
    ) {
        requestCommit(request = {
            Api.apiClient()
                .dealOrderDetail(
                    dto = dto,
                )
        }, resp = {
            dealOrderDetailLiveData.postValue(it)
        })
    }


    //问题类型统计
    fun quaTypeCount(
        startTime: String? = null,
        endTime: String? = null,
    ) {
        requestCommit(request = {
            Api.apiClient()
                .quaTypeCount(
                    startTime = startTime,
                    endTime = endTime,
                )
        }, resp = {
            quaTypeCountListLiveData.postValue(it)
        })
    }

    fun getWrongRec(
        startTime: String?,
        endTime: String?,
        pageNo: Int,
        pageSize: Int,
        equModel: String?
    ) {
        requestCommit(request = {
            Api.apiClient()
                .getWrongRec(
                    startTime = startTime,
                    endTime = endTime,
                    pageNo = pageNo,
                    pageSize = pageSize,
                    equModel = equModel
                )
        }, resp = {
            wrongRecVoListLiveData.postValue(it)
        })
    }

    fun OperationStatistics(
        userId: String? = null,
        trcd: String?,
        onlineRate: String?,
        comments: String?,
    ) {
        requestCommit(request = {
            Api.apiClient()
                .OperationStatistics(
                    userId = userId,
                    trcd = trcd,
                    onlineRate = onlineRate,
                    comments = comments,

                    )
        }, resp = {
            gwRunningStaticVoListLiveData.postValue(it)
        })
    }
}